// pages/share/share.js

const app = getApp()
var server = app.globalData.server;
var appid = app.globalData.appid;
Page({

    /**
     * 页面的初始数据
     */
    data: {
        pages: 1,
        currentPage: 1,
        size: 20,
        userInfo: {},
        img_url: app.globalData.cloud_url,
        zanNum:0,
        actionSheetHidden: true,
        painting: {},
        shareImage: '',
        qrcode: '',
        zanLog:[]
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function(options) {
      this.getData()
      var that =this
        let userInfo = wx.getStorageSync('userInfo')
        if (userInfo) {
            this.setData({
                userInfo: userInfo
            })
        }
    },
  getData(){
    //查询点赞用户
    wx.showLoading({ //期间为了显示效果可以添加一个过度的弹出框提示“加载中”  
      title: '加载中',
      icon: 'loading',
    });
    var that = this
    console.log(app.globalData.openid)
    const db = wx.cloud.database()
    db.collection('zan_user').count({
      success: function (res) {
        wx.hideLoading();
        that.setData({
          zanNum: res.total,
          pages: Math.ceil(res.total / that.data.size)
        })
        db.collection('zan_user')
          .skip(that.data.size * (that.data.currentPage - 1))
          .limit(that.data.size) // 限制返回数量
          .where({
          })
          .orderBy('zan_time', 'desc')  // desc 倒 asc 正
          .get({
            success: res => {
              console.log('[数据库] [查询记录] 成功: ', res)
              console.log(res.data)
              var zanLog = that.data.zanLog
              for (var i = 0; i < res.data.length; i++) {
                zanLog.push(res.data[i])
              }
              that.setData({
                zanLog: zanLog
              })
            },
            fail: err => {
              wx.showToast({
                icon: 'none',
                title: '操作失败'
              })
              console.error('[数据库] [查询记录] 失败：', err)
            }
          })
      }
    })
  },
  /**
* 页面上拉触底事件的处理函数
*/
  onReachBottom: function () {
    console.log('a')
    if (this.data.pages <= this.data.currentPage) {
      wx.showToast({
        title: '无更多数据',
        icon: 'none',
        duration: 1000
      });
    } else {
      this.setData({
        currentPage: this.data.currentPage + 1
      })
      this.getData();
    }
  },
    openActionsheet: function() {
        var self = this;
        self.setData({
            actionSheetHidden: !self.data.actionSheetHidden
        });
    },
    listenerActionSheet: function() {
        var self = this;
        self.setData({
            actionSheetHidden: !self.data.actionSheetHidden
        })
    },
    createPoster: function() {

        wx.navigateTo({
            url: '/pages/poster/index',
        })
    },
    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function() {

    },
    
  //下拉刷新
  onPullDownRefresh: function () {
    var that = this
    setTimeout(function () {
      wx.stopPullDownRefresh() //停止刷新
      that.setData({
        currentPage: 1,
        zanLog: []
      })
      that.onLoad()
    }, 1000);
  },
    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function() {
        var that = this;
        //console.log(that.data);
        return {
            title: '婚礼邀请函',
          path: 'pages/Wedding/Wedding',
            success: function(res) {
                wx.showToast({
                    title: '分享成功',
                })
            },
            fail: function(res) {
                // 转发失败
                wx.showToast({
                    title: '分享取消',
                })
            }
        }
    },
    bindgetuserinfo: function(e) {
        console.log(e.detail.userInfo)
        var that = this;
        if (e.detail.userInfo) {
            wx.setStorageSync('userInfo', e.detail.userInfo)
            that.setData({
                userInfo: e.detail.userInfo,
                authBtn: false
            })
          console.log(that.data.userInfo)
          wx.showToast({
            title: '授权成功',
            duration: 2000,
            success: function () {
              setTimeout(function () {
                wx.showToast({
                  title: "你可以送祝福啦~",
                  icon: 'none',
                  duration: 2000
                });
              }, 2000)
            }
          })
        } else {
            wx.showToast({
                title: "为了您更好的体验,请先同意授权",
                icon: 'none',
                duration: 2000
            });
        }
    },

    zan: function(event) {
      //查询点赞用户
      var that= this
      console.log(app.globalData.openid)
      const db = wx.cloud.database()
      db.collection('zan_user').where({
        _openid: app.globalData.openid
      }).get({
        success: res => {
          console.log('[数据库] [查询记录] 成功: ', res)
          if(res.data.length >0){
            wx.showToast({
              icon: 'none',
              title: '你已祝福过啦~'
            })
          }else{
            that.zanClick();
          }
        },
        fail: err => {
          wx.showToast({
            icon: 'none',
            title: '操作失败'
          })
          console.error('[数据库] [查询记录] 失败：', err)
        }
      })
    },
  zanClick(){
    var that =this
    var userInfo = this.data.userInfo;
    var zan_time = new Date(+new Date() + 8 * 3600 * 1000).toISOString().replace(/T/g, ' ').replace(/\.[\d]{3}Z/, '')
    console.log(userInfo)
    const db = wx.cloud.database()
    db.collection('zan_user').add({
      data: {
        nickName: userInfo.nickName,
        avatarUrl: userInfo.avatarUrl,
        zan_time
      },
      success: res => {
        // 在返回结果中会包含新创建的记录的 _id
        wx.showToast({
          title: '祝福成功',
        })
        console.log('[数据库] [新增记录] 成功，记录 _id: ', res._id)
        that.setData({
          currentPage: 1,
          zanLog: []
        })
        that.getData()
      },
      fail: err => {
        wx.showToast({
          icon: 'none',
          title: '祝福失败'
        })
        console.error('[数据库] [新增记录] 失败：', err)
      }
    })
  }
})